#include "WorkerImage.h"
#include "Utils/Log.h"
#include "Utils/AlgUtils.h"
#include <opencv2/opencv.hpp>
#include "Analyzer.h"

namespace AVSAnalyzer {

WorkerImage::WorkerImage(Scheduler* scheduler, Control* control) 
    : Worker(scheduler, control), 
      mImageProcessThread(nullptr),
      mImageData(nullptr),
      mImageSize(0)
{
    // 初始化基类Worker已完成
}

WorkerImage::~WorkerImage()
{
    if (mImageData) {
        delete[] mImageData;
        mImageData = nullptr;
    }
    // 基类析构函数会自动调用
}

bool WorkerImage::startImageProcess(const char* imageData, int imageSize, std::string& msg)
{
    // 保存图片数据
    mImageData = new char[imageSize];
    mImageSize = imageSize;
    memcpy(mImageData, imageData, imageSize);
    
    // 初始化分析器
    this->mAnalyzer = new Analyzer(mScheduler, mControl);
    
    // 启动图片处理线程
    mImageProcessThread = new std::thread(WorkerImage::imageProcessThreadWrapper, this);
    mThreads.push_back(mImageProcessThread);
    
    mState = true;
    return true;
}

void WorkerImage::imageProcessThreadWrapper(void* arg)
{
    WorkerImage* worker = static_cast<WorkerImage*>(arg);
    worker->imageProcessThread();
}

void WorkerImage::imageProcessThread()
{
    // 从内存中解码图片
    std::vector<uchar> buffer(mImageData, mImageData + mImageSize);
    cv::Mat image = cv::imdecode(buffer, cv::IMREAD_COLOR);
    
    if(image.empty()) {
        LOGE("Failed to decode image data, size: %d", mImageSize);
        return;
    }
    
    // 准备分析参数
    bool happen = false;
    float happenScore = 0.0;
    std::vector<DetectObject> happenDetects;
    int64_t frameCount = 0;
    
    // 执行分析
    mAnalyzer->handleVideoFrame(frameCount, image, happenDetects, happen, happenScore);
    
    // 保存检测结果到成员变量
    mDetectResults = happenDetects;
    
    // 绘制检测结果
    if(happenDetects.size() > 0) {
        int x1, y1, x2, y2;
        for (size_t i = 0; i < happenDetects.size(); i++)
        {
            x1 = happenDetects[i].x1;
            y1 = happenDetects[i].y1;
            x2 = happenDetects[i].x2;
            y2 = happenDetects[i].y2;

            // 根据class_id选择颜色
            int color_idx = ((happenDetects[i].class_id) % AVSAnalyzer::COLORS.size());
            cv::Scalar color = AVSAnalyzer::COLORS[color_idx];

            // 计算线宽
            int line_width = 3;

            // 绘制得分和目标class_name
            std::string class_name = happenDetects[i].class_name;
            float class_score = happenDetects[i].class_score;
            std::stringstream class_score_ss;
            class_score_ss << std::fixed << std::setprecision(0) << (class_score*100.0f);
            std::string title = class_name + ":" + class_score_ss.str() + "%";

            // 绘制检测框
            cv::rectangle(image, 
                        cv::Rect(x1, y1, (x2 - x1), (y2 - y1)),
                        color,
                        line_width,
                        cv::LINE_8,
                        0);

            // 绘制文本
            int text_x = x1;
            int text_y = y1 - 5;
            
            if(mFtValid)
            {
                // 计算文本尺寸
                int text_width = 0;
                int text_height = 0;
                calculateTextSize(title, text_width, text_height);
                
                // 绘制背景和文本
                int padding = 4;
                cv::Rect bg_rect(
                    text_x - padding, 
                    text_y - text_height - padding,
                    text_width + (padding * 2),
                    text_height + (padding * 2)
                );
                
                cv::rectangle(image, bg_rect, color, -1);
                drawChineseText(image, title, text_x, text_y, cv::Scalar(0, 0, 0));
            }
            else
            {
                int font_size = 6 * std::min(image.cols, image.rows) / 180;
                cv::putText(image,
                        title,
                        cv::Point(text_x, text_y),
                        cv::FONT_HERSHEY_SIMPLEX,
                        font_size / 60.0f,
                        color,
                        line_width);
            }
        }
    }
    
    // 保存报警图片(如果触发了报警)，暂时不需要出发报警生成
    // if(happen) {
    //     mAlarmImageGenerator->saveAlarmImage(image, happenScore);
    // }
    
    // 清理内存
    delete[] mImageData;
    mImageData = nullptr;
    mImageSize = 0;
    
    // 标记处理完成
    mState = false;
}

} // namespace AVSAnalyzer